package mini.statement;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Random;

import mini.StatementList;
import mini.compiler.CodeGenerator;
import mini.expr.Expr;

/**
 * If statement Generation
 * 
 * @author Meyer
 */
public class IfStatement extends Statement {

	private Expr expr;
    private StatementList s1, s2;
    private int labelNo=0;

    
    /**
     * Default Constructor - called by CUP
     * @param e
     * @param list1
     * @param list2
     */
    public IfStatement(Expr e, StatementList list1, StatementList list2){
		expr = e;
		s1 = list1;
		s2 = list2;
    }
 
    /**
     * If construction with no else statement
     * @param e
     * @param list
     */
    public IfStatement(Expr e, StatementList list){
		expr = e;
		s1 = list;
    }

    /* (non-Javadoc)
     * @see mini.statement.Statement#eval(java.util.HashMap, java.util.LinkedList)
     */
    public void eval(HashMap hm, LinkedList var){
		if (expr.eval(hm)>0){
		    s1.eval(hm,var);
		}
		else{
		    s2.eval(hm,var);
		}
    }

    /**
     * Creates the "assembly code"
     * if_statement ->
     *	 if expr then statement1
     *	 else statement 2
     *	 fi
     *	   <=>
     *	 if expr > 0 then statement 1
     *	 else statement 2
     *	 endif
     * @see mini.statement.Statement#parse(java.util.HashMap, java.util.LinkedList)
     */
    public String parse(HashMap hm, LinkedList var){
    	
    	String label1 = nextTempLocation();
    	String label2 = nextTempLocation();

    	CodeGenerator cg = new CodeGenerator();
    	
    	// Do what you need to in order to evaluate/load expression
    	String exprValue = expr.parse(hm);
    	cg.appendCode(  exprValue );
    	cg.addLoadAccumulator( expr.getTempVariable() );
    	
    	// JMN, jump if it is negative
    	cg.addJMN( label1 );
    	// JMZ, jump if it is 0
    	cg.addJMZ( label1 );
    	cg.appendCode(s1.parse(hm, var));
    	cg.addJMP( label2 );
    	cg.appendCode(label1 +": "+s2.parse(hm, var));
    	cg.addLabel(label2);
    	//Return the code
    	return cg.getCode();
    	
    }
}
